package com.cskaoyan.app.wxservice.impl;

import com.cskaoyan.app.bean.bo.WxGoodsListBO;
import com.cskaoyan.app.bean.common.CommonData;
import com.cskaoyan.app.bean.po.*;
import com.cskaoyan.app.bean.vo.wx.*;
import com.cskaoyan.app.mapper.*;
import com.cskaoyan.app.util.StringsUtil;
import com.cskaoyan.app.wxservice.WxGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    private MarketGoodsMapper goodsMapper;

    @Autowired
    private MarketCategoryMapper categoryMapper;

    @Autowired
    private MarketGoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    private MarketBrandMapper brandMapper;

    @Autowired
    private MarketCommentMapper commentMapper;

    @Autowired
    private MarketIssueMapper issueMapper;

    @Autowired
    private MarketGoodsProductMapper goodsProductMapper;

    @Autowired
    private MarketSystemMapper systemMapper;

    @Autowired
    private MarketGoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    private MarketCollectMapper collectMapper;

    @Autowired
    private MarketUserMapper userMapper;

    @Autowired
    private MarketSearchHistoryMapper historyMapper;

    @Override
    public Integer count() {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andDeletedEqualTo(false);
        long count = goodsMapper.countByExample(example);
        return Math.toIntExact(count);
    }

    @Override
    public WxGoodsCategoryVO category(Integer id) {
        List<MarketCategory> brotherCategory;
        MarketCategory currentCategory;
        MarketCategory parentCategory;

        MarketCategoryExample example = new MarketCategoryExample();
        MarketCategory category = categoryMapper.selectByPrimaryKey(id);
        Integer pid = category.getPid();
        if (pid == 0) {
            parentCategory = category;
            example.createCriteria().andPidEqualTo(id).andDeletedEqualTo(false);
            brotherCategory = categoryMapper.selectByExample(example);
            currentCategory = brotherCategory.get(0);
        } else {
            currentCategory = category;
            parentCategory = categoryMapper.selectByPrimaryKey(category.getPid());
            example.createCriteria().andPidEqualTo(category.getPid()).andDeletedEqualTo(false);
            brotherCategory = categoryMapper.selectByExample(example);
        }
        return new WxGoodsCategoryVO(brotherCategory, currentCategory, parentCategory);
    }

    @Override
    public WxGoodsListVO list(WxGoodsListBO info) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.setOrderByClause(StringsUtil.getOrderClause(info.getSort(), info.getOrder()));

        Integer categoryId = info.getCategoryId();
        String keyword = info.getKeyword();
        String isHot = info.getIsHot();
        String isNew = info.getIsNew();
        Integer brandId = info.getBrandId();
        Integer userid = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userid");

        if (categoryId != null && categoryId == 0) {
            if (!StringsUtil.isEmpty(keyword)) {
                goodsExample.createCriteria().andNameLike(StringsUtil.getConcat(keyword)).andDeletedEqualTo(false);
                if (userid != null) {
                    MarketSearchHistory history = new MarketSearchHistory();
                    MarketSearchHistoryExample historyExample = new MarketSearchHistoryExample();
                    historyExample.or().andUserIdEqualTo(userid).andKeywordEqualTo(keyword).andDeletedEqualTo(false);
                    long count = historyMapper.countByExample(historyExample);
                    if (count == 0) {
                        history.setUserId(userid);
                        history.setKeyword(keyword);
                        history.setAddTime(new Date());
                        history.setUpdateTime(new Date());
                        historyMapper.insertSelective(history);
                    } else {
                        history.setUpdateTime(new Date());
                        historyMapper.updateByExampleSelective(history, historyExample);
                    }
                }
            } else if (!StringsUtil.isEmpty(isHot)) {
                goodsExample.createCriteria().andIsHotEqualTo("true".equals(isHot)).andDeletedEqualTo(false);
            } else if (!StringsUtil.isEmpty(isNew)) {
                goodsExample.createCriteria().andIsNewEqualTo("true".equals(isNew)).andDeletedEqualTo(false);
            } else {
                return new WxGoodsListVO(0, 0, 0, 0, new ArrayList<>(), new ArrayList<>());
            }
        } else if (categoryId != null) {
            if (!StringsUtil.isEmpty(keyword)) {
                goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andNameLike(StringsUtil.getConcat(keyword)).andDeletedEqualTo(false);
            } else if (!StringsUtil.isEmpty(isHot)) {
                goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andIsHotEqualTo("true".equals(isHot)).andDeletedEqualTo(false);
            } else if ((!StringsUtil.isEmpty(isNew))) {
                goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andIsNewEqualTo("true".equals(isNew)).andDeletedEqualTo(false);
            } else {
                goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
            }
        } else if (brandId != null) {
            goodsExample.or().andBrandIdEqualTo(brandId).andDeletedEqualTo(false);
        }

        PageHelper.startPage(info.getPage(), info.getLimit());
        List<MarketGoods> list = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        PageHelper.clearPage();

        PageInfo<MarketGoods> pageInfo = new PageInfo<>(list);

        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.createCriteria().andLevelEqualTo("L2").andDeletedEqualTo(false);

        PageHelper.startPage(1, 20);
        List<MarketCategory> filterCategoryList = categoryMapper.selectByExample(categoryExample);
        PageHelper.clearPage();

        return new WxGoodsListVO(((int) pageInfo.getTotal()), pageInfo.getPages(), pageInfo.getPageSize(), pageInfo.getPageNum(), pageInfo.getList(), filterCategoryList);
    }

    @Override
    public CommonData<MarketGoods> related(Integer id) {
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andCategoryIdEqualTo(marketGoods.getCategoryId()).andDeletedEqualTo(false);

        PageHelper.startPage(1, 6);
        List<MarketGoods> goodsList = goodsMapper.selectByExampleWithBLOBs(example);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(goodsList);

        return CommonData.data(pageInfo);
    }

    @Override
    public WxGoodsDetailVO detail(Integer id) {
        MarketGoods info = goodsMapper.selectByPrimaryKey(id);
        Integer goodsId = info.getId();
        Integer brandId = info.getBrandId();
        MarketBrand brand = brandMapper.selectByPrimaryKey(brandId);

        MarketGoodsAttributeExample goodsAttributeExample = new MarketGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<MarketGoodsAttribute> attribute = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(goodsId).andTypeEqualTo((byte) 0).andDeletedEqualTo(false);
        PageHelper.startPage(1, 2);
        List<MarketComment> commentList = commentMapper.selectByExample(commentExample);
        PageHelper.clearPage();
        PageInfo<MarketComment> pageInfo = new PageInfo<>(commentList);
        int count = (int) pageInfo.getTotal();

        List<MarketUser> userList = userMapper.selectByExample(null);
        Map<Integer, String> nicknameMap = new HashMap<>();
        Map<Integer, String> avatarMap = new HashMap<>();
        for (MarketUser user : userList) {
            nicknameMap.put(user.getId(), user.getNickname());
            avatarMap.put(user.getId(), user.getAvatar());
        }

        List<WxGoodsCommentVO> data = new ArrayList<>();
        for (MarketComment comment : commentList) {
            data.add(new WxGoodsCommentVO(comment.getAddTime(), comment.getPicUrls(), comment.getAdminContent(), nicknameMap.get(comment.getUserId()), comment.getId(), avatarMap.get(comment.getUserId()), comment.getContent()));
        }
        WxGoodsDetailCommentVO comment = new WxGoodsDetailCommentVO(count, data);

        MarketIssueExample issueExample = new MarketIssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        List<MarketIssue> issue = issueMapper.selectByExample(issueExample);

        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<MarketGoodsProduct> productList = goodsProductMapper.selectByExample(goodsProductExample);

        MarketSystemExample systemExample = new MarketSystemExample();
        systemExample.createCriteria().andKeyNameEqualTo("market_wx_share").andDeletedEqualTo(false);
        List<MarketSystem> systemList = systemMapper.selectByExample(systemExample);
        String keyValue = systemList.get(0).getKeyValue();
        boolean share = "true".equals(keyValue);

        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.createCriteria().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<MarketGoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(specificationExample);

        Map<String, List<MarketGoodsSpecification>> specMap = new LinkedHashMap<>();
        for (MarketGoodsSpecification spec : goodsSpecifications) {
            List<MarketGoodsSpecification> valueList = specMap.get(spec.getSpecification());
            if (valueList == null) {
                valueList = new ArrayList<>();
                specMap.put(spec.getSpecification(), valueList);
            }
            valueList.add(spec);
        }

        // List<Map<String, Object>> specificationList = new ArrayList<>();
        // for (Map.Entry<String, List<MarketGoodsSpecification>> entry : specMap.entrySet()) {
        //     Map<String, Object> newMap = new HashMap<>();
        //     String name = entry.getKey();
        //     List<MarketGoodsSpecification> valueList = entry.getValue();
        //     newMap.put("name", name);
        //     newMap.put("valueList", valueList);
        //     specificationList.add(newMap);
        // }

        List<WxGoodsDetailSpecVO> specificationList = new ArrayList<>();
        for (Map.Entry<String, List<MarketGoodsSpecification>> entry : specMap.entrySet()) {
            String name = entry.getKey();
            List<MarketGoodsSpecification> valueList = entry.getValue();
            specificationList.add(new WxGoodsDetailSpecVO(name, valueList));
        }

        int userHasCollect = 0;
        Integer userid = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userid");
        if (userid != null) {
            MarketCollectExample collectExample = new MarketCollectExample();
            collectExample.createCriteria().andUserIdEqualTo(userid).andValueIdEqualTo(goodsId).andTypeEqualTo((byte) 0).andDeletedEqualTo(false);
            int num = (int) collectMapper.countByExample(collectExample);
            if (num == 1) userHasCollect = 1;
        }

        return new WxGoodsDetailVO(attribute, brand, comment, new ArrayList<>(), info, issue, productList, share, "", specificationList, userHasCollect);
    }
}
